import os
import sys
import platform
import subprocess
import urllib.request

# 运行命令
def run_command(command):
    print(f"运行命令: {' '.join(command)}")
    try:
        result = subprocess.run(command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print(f"命令失败: {e}")
        print(f"错误输出: {e.stderr}")
        return False

# 检查库是否已安装
def check_library_installed(library_name):
    try:
        __import__(library_name)
        print(f"{library_name} 已安装")
        return True
    except ImportError:
        print(f"{library_name} 未安装")
        return False

# 主函数
def main():
    print("===== dlib和face_recognition安装脚本 ======")

    # 检查是否已安装
    if check_library_installed("dlib") and check_library_installed("face_recognition"):
        print("\n所有库已安装!")
        return

    # 获取系统信息
    python_version = f"{sys.version_info.major}.{sys.version_info.minor}"
    architecture = "64位" if platform.machine().endswith('64') else "32位"
    print(f"Python版本: {python_version}")
    print(f"系统架构: {architecture}")

    # 尝试安装dlib (不指定版本，让pip自动选择兼容版本)
    print("\n尝试安装dlib...")
    if not run_command([sys.executable, "-m", "pip", "install", "dlib", "-i", "https://pypi.tuna.tsinghua.edu.cn/simple", "--default-timeout=120"]):
        print("\ndlib安装失败，尝试使用预编译wheel文件...")
        print("\n手动下载指南:")
        print("1. 访问: https://pypi.org/project/dlib/#files")
        print(f"2. 下载适合您Python版本({python_version})和系统架构({architecture})的wheel文件")
        print("3. 将文件放在当前目录")
        print("4. 运行命令: pip install [下载的wheel文件名]")
        print("5. 然后运行: pip install face_recognition -i https://pypi.tuna.tsinghua.edu.cn/simple")
        return

    # 验证dlib安装
    if not check_library_installed("dlib"):
        print("dlib验证失败")
        return

    # 安装face_recognition
    print("\n尝试安装face_recognition...")
    if not run_command([sys.executable, "-m", "pip", "install", "face_recognition", "-i", "https://pypi.tuna.tsinghua.edu.cn/simple", "--default-timeout=120"]):
        print("face_recognition安装失败")
        return

    # 验证face_recognition安装
    if not check_library_installed("face_recognition"):
        print("face_recognition验证失败")
        return

    print("\n===== 所有安装完成! ======")

if __name__ == "__main__":
    main()